package com.alex.wechat.mp.menu.service.impl;

import java.io.Serializable;
import java.util.List;

import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.menu.entity.WxMenuEntity;
import com.alex.wechat.mp.menu.service.MenuTreeBuilder;
import com.alex.wechat.mp.menu.service.WxMenuServiceI;
import com.gomore.jeecg.common.Assert;

import me.chanjar.weixin.common.bean.menu.WxMenu;

@Service("wxMenuService")
@Transactional
public class WxMenuServiceImpl extends CommonServiceImpl implements WxMenuServiceI {

  @Autowired
  private MenuTreeBuilder menuTreeBuilder;

  public <T> void delete(T entity) {
    super.delete(entity);
    // 执行删除操作配置的sql增强
    this.doDelSql((WxMenuEntity) entity);
  }

  public <T> Serializable save(T entity) {
    if (WxContext.getWxAccount() == null) {
      throw new RuntimeException("请先设置微信公众号");
    }
    WxMenuEntity menuEntity = (WxMenuEntity) entity;
    menuEntity.setAccountId(WxContext.getOriginalId());
    Serializable t = super.save(entity);
    // 执行新增操作配置的sql增强
    this.doAddSql((WxMenuEntity) entity);
    return t;
  }

  public <T> void saveOrUpdate(T entity) {
    super.saveOrUpdate(entity);
    // 执行更新操作配置的sql增强
    this.doUpdateSql((WxMenuEntity) entity);
  }

  /**
   * 默认按钮-sql增强-新增操作
   * 
   * @param id
   * @return
   */
  public boolean doAddSql(WxMenuEntity t) {
    return true;
  }

  /**
   * 默认按钮-sql增强-更新操作
   * 
   * @param id
   * @return
   */
  public boolean doUpdateSql(WxMenuEntity t) {
    return true;
  }

  /**
   * 默认按钮-sql增强-删除操作
   * 
   * @param id
   * @return
   */
  public boolean doDelSql(WxMenuEntity t) {
    return true;
  }

  @Override
  @Transactional(readOnly = true)
  public WxMenu buildWxMenu() {
    if (WxContext.getWxAccount() == null) {
      throw new RuntimeException("请先设置微信公众号");
    }

    String hql = "from " + WxMenuEntity.class.getName() + " where accountId = ?";
    final List<WxMenuEntity> sourceMenus = findByHql(hql, WxContext.getOriginalId());
    WxMenu wxMenu = menuTreeBuilder.buildWxMenuTree(sourceMenus);
    return wxMenu;
  }

  @Override
  @Transactional(readOnly = true)
  public WxMenuEntity getByKey(String accountId, String menuKey) {
    Assert.assertArgumentNotEmpty(accountId, "accountId");
    Assert.assertArgumentNotEmpty(menuKey, "menuKey");

    String hql = "from " + WxMenuEntity.class.getName() + " where accountId = ? and menuKey = ?";
    List<WxMenuEntity> results = findByHql(hql, accountId, menuKey);
    return results.isEmpty() ? null : results.get(0);
  }

}